package com.starnet.yarnmonitor.security.handler;

import com.alibaba.fastjson.JSON;
import com.starnet.yarnmonitor.security.utils.RedisCache;
import com.starnet.yarnmonitor.yarn.vo.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    RedisCache redisCache;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        User user = (User) authentication.getPrincipal();
        String username = user.getUsername();
        boolean isSuccess = redisCache.deleteObject("login:" + username);
        Result result ;
        if (isSuccess){
           result=Result.success("注销成功");
        }else {
            result = Result.fail("注销失败");
        }

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(result));
    }
}
